import axios from 'axios';
import qs from 'qs'
import {
  Notification,
  MessageBox
} from 'element-ui'
import {
  getToken
} from '@/common/utils/user.js'
// 创建axios实例
const service = axios.create({
  // baseURL: process.env.BASE_API, // api的base_url
  timeout: 40000, // 请求超时时间
  headers: {
    'Cache-Control': 'no-cache'
  }

});
// 路由请求拦截
// http request 拦截器
service.interceptors.request.use(
  config => {
    config.headers['auth_token'] = getToken();
    if (config.method === 'post' || config.method === 'get') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
      config.transformRequest = [function(data, headers) {
        return qs.stringify(data);
      }];
    } else if (config.method === 'put') {
      config.headers['Content-Type'] = 'application/json;charset=UTF-8';
      config.transformRequest = [function(data, headers) {
        return JSON.stringify(data);
      }];
    }
    return config;
  }, error => {
    Notification.error({
      message: '服务器失去连接!'
    })
    return Promise.reject(error);
  });
service.interceptors.response.use(
  repsonse => {
    if (repsonse.data.status == 500) {
      Notification.warning({
        title: '系统提示',
        message: repsonse.data.msg
      })
    } else if (repsonse.data.status == 501) {
      Notification.error({
        title: '系统异常',
        message: repsonse.data.msg
      })
    } else if (repsonse.data.status == 502) {
      Notification.warning({
        title: '权限问题',
        message: repsonse.data.msg
      })
      window.location.href = "/"
    }else if (repsonse.data.status == 503){
      MessageBox({
        title: '系统提示',
        dangerouslyUseHTMLString: true,
        message: repsonse.data.msg
      })
    }
    return repsonse;
  },
  error => {
    Notification.error({
      title: '异常',
      message: '请求超时!'
    })
    return Promise.reject(error);
  });
export default service;
